<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/11/30
 * Time: 14:13
 */

namespace app\admin\controller;


use think\Db;
use think\Request;

class Building extends Base
{
    /**
     * 首页展示
     * @return mixed|\think\response\Json
     */
    public function index()
    {
        if(Request::instance()->isAjax()) {
            $params = input('param.');
            $where = [];
            //名称
            if(isset($params['in_name']) && $params['in_name'] != "") {
                $where['uiw.in_name'] = ['like', "%" . $params['in_name'] . "%"];
            }
            //规格类型
            if(isset($params['spec_type_id']) && $params['spec_type_id'] != '') {
                $where['uiw.spec_type_id'] = $params['spec_type_id'];
            }
            //房屋类型
            if(isset($params['house_type_id']) && $params['house_type_id'] != '') {
                $where['uiw.house_type_id'] = $params['house_type_id'];
            }
            //仓库
            if(isset($params['house_id']) && $params['house_id'] != '') {
                $where['uiw.warehouse_id'] = $params['house_id'];
            }
            //状态
            if(isset($params['in_status']) && $params['in_status'] != ''){
                $where['uiw.in_status'] = $params['in_status'];
            }
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;// 获取总条数;
            $count = Db::table('up_in_warehouse')
                ->alias('uiw')
                ->join('up_u_user uuu', 'uuu.user_id = uiw.in_user_id', 'left')
                ->join('up_u_user uuu1', 'uuu1.user_id = uiw.check_user_id', 'left')
                ->join('up_house_type uht', 'uht.house_type_id = uiw.house_type_id', 'left')
                ->join('up_spec_type ust', 'ust.spec_type_id = uiw.spec_type_id', 'left')
                ->join('up_warehouse uw', 'uw.house_id = uiw.warehouse_id', 'left')
                ->where($where)
                ->count();
            $lists = Db::table('up_in_warehouse')
                ->alias('uiw')
                ->join('up_u_user uuu', 'uuu.user_id = uiw.in_user_id', 'left')
                ->join('up_u_user uuu1', 'uuu1.user_id = uiw.check_user_id', 'left')
                ->join('up_house_type uht', 'uht.house_type_id = uiw.house_type_id', 'left')
                ->join('up_spec_type ust', 'ust.spec_type_id = uiw.spec_type_id', 'left')
                ->join('up_warehouse uw', 'uw.house_id = uiw.warehouse_id', 'left')
                ->field(['in_id', 'create_time', 'in_num', 'house_type', 'spec_type', 'warehouse_name',
                    'uuu.user_username', 'uuu1.user_username' => 'check_user', 'check_user_id',
                    'in_name', "concat('".http_type()."',in_img)"=>'in_img', 'in_status', 'in_abstract',
                'in_detail_address'])
                ->page($Nowpage, $limits)
                ->where($where)
                ->order('create_time desc')
                ->select();
            foreach($lists as $key => &$vo){
                if($vo['check_user_id'] == -1) $vo['check_user'] = 'admin';
            }
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        if(session('?in_id')){
            session('in_id',null);
        }
        //规格类型
        $specType = Db::table('up_spec_type')
            ->field('spec_type_id, spec_type')
            ->select();
        //房屋类型
        $houseType = Db::table('up_house_type')
            ->field('house_type_id, house_type')
            ->select();
        //仓库
        $warehouse = Db::table('up_warehouse')
            ->field('house_id, warehouse_name')
            ->select();
        $this->assign([
            'specType' => $specType,
            'houseType' => $houseType,
            'warehouse' => $warehouse
        ]);
        return $this->fetch();
    }
    
    /**
     * 入库物件审核
     * @return mixed|\think\response\Json
     */
    public function audit(){
        if(Request::instance()->isPost()){
            $in_status = input('param.in_status');
            $id = input('param.in_id');
            $data = [
                'in_status' => $in_status,//状态  2 通过  2 不通过
                'check_user_id' => -1,//审核者，后台审核时为-1
                'check_time' => date('Y-m-d H:i:s'),//审核时间
            ];
            $res = Db::table('up_in_warehouse')->where('in_id', $id)->update($data);
            if($res){
                return json(['code' => 200, 'msg' => '审核成功', 'data' => '']);
            }else{
                return json(['code' => 100, 'msg' => '审核失败', 'data' => '']);
            }
        }
        $in_id = input('param.id');
        $info = Db::table('up_in_warehouse')
            ->alias('uiw')
            ->join('up_u_user uuu', 'uuu.user_id = uiw.in_user_id', 'left')
            ->join('up_house_type uht', 'uht.house_type_id = uiw.house_type_id', 'left')
            ->join('up_spec_type ust', 'ust.spec_type_id = uiw.spec_type_id', 'left')
            ->join('up_warehouse uw', 'uw.house_id = uiw.warehouse_id', 'left')
            ->field(['in_num', 'in_name', "concat('".http_type()."',in_img)"=>'in_img',
                'in_address', 'in_abstract', 'create_time', 'user_username', 'house_type', 'spec_type',
            'warehouse_name', 'in_id', 'in_detail_address'])
            ->where('in_id', $in_id)
            ->find();
        $this->assign('info', $info);
        return $this->fetch();
    }
    
    /**
     * 删除
     * @return \think\response\Json
     */
    public function delBuilding(){
        $in_id = input('param.id');
        Db::startTrans();
        try{
            Db::table('up_in_warehouse')->delete($in_id);
            Db::table('up_jia')->where('jia_ku_id', $in_id)->delete();
            Db::commit();
            $res = true;
        }catch(\Exception $e){
            Db::rollback();
            $res = false;
        }
        if($res){
            return json(['code'=>200,'msg'=>'删除成功']);
        }else{
            return json(['code'=>100,'msg'=>'删除失败']);
        }
    }
    
    /**
     * 编辑缩略图
     * @return mixed|\think\response\Json
     */
    public function editThumb(){
        if(Request::instance()->isPost()){
            $in_img = input('param.in_img');
            $in_id = input('param.in_id');
            if(empty($in_img)){
                return json(['code' => 100, 'msg' => '请上传图片', 'data' => '']);
            }
            $res = Db::table('up_in_warehouse')->where('in_id', $in_id)->setField('in_img', $in_img);
            if($res){
                return json(['code' => 200, 'msg' => '编辑成功', 'data' => '']);
            }else{
                return json(['code' => 100, 'msg' => '编辑失败', 'data' => '']);
            }
        }
        $in_id = input('param.id');
        $info = Db::table('up_in_warehouse')
            ->field(["concat('".http_type()."',in_img)"=>'in_img', 'in_id'])
            ->where('in_id', $in_id)
            ->find();
        return $this->fetch('building/editthumb', ['info'=>$info]);
    }
    
    /**
     * 自定义属性列表展示
     * @return mixed|\think\response\Json
     */
    public function costun(){
        if(Request::instance()->isAjax()) {
            $in_id = input('param.id');
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;// 获取总条数;
            $count = Db::table('up_jia')->where('jia_ku_id', $in_id)->count();
            $lists = Db::table('up_jia')
                ->field('jia_id, jia_name, jia_value')
                ->page($Nowpage, $limits)
                ->where('jia_ku_id', $in_id)
                ->order('jia_id desc')
                ->select();
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $param = input('param.');
        if(!session('?in_id')){
            session('in_id',$param['id']);
        }
        return $this->fetch();
    }
    
    /**
     * 添加自定义属性
     * @return mixed|\think\response\Json
     */
    public function addCostun(){
        if(Request::instance()->isPost()){
            $params = input('param.');
            $data = [
                'jia_name' => $params['jia_name'],//名称
                'jia_value' => $params['jia_value'],//属性
                'jia_ku_id' => session('in_id'),//所属物件
            ];
            $res = Db::table('up_jia')->insert($data);
            if($res){
                return json(['code' => 200, 'msg' => '添加成功', 'data' => '']);
            }else{
                return json(['code' => 100, 'msg' => '添加失败', 'data' => '']);
            }
        }
        return $this->fetch('building/addcostun');
    }
    
    /**
     * 编辑自定义属性
     * @return mixed|\think\response\Json
     */
    public function editCostun(){
        if(Request::instance()->isPost()){
            $params = input('param.');
            $data = [
                'jia_name' => $params['jia_name'],//名称
                'jia_value' => $params['jia_value'],//属性
            ];
            $res = Db::table('up_jia')->where('jia_id', $params['jia_id'])->update($data);
            if($res){
                return json(['code' => 200, 'msg' => '编辑成功', 'data' => '']);
            }else{
                return json(['code' => 100, 'msg' => '编辑失败', 'data' => '']);
            }
        }
        $jia_id = input('param.id');
        $info = Db::table('up_jia')->where('jia_id', $jia_id)->find();
        $this->assign('info', $info);
        return $this->fetch('building/editcostun');
    }
    
    /**
     * 删除自定义属性
     * @return \think\response\Json
     */
    public function delCostun(){
        $jia_id = input('param.id');
        $res = Db::table('up_jia')->delete($jia_id);
        if($res){
            return json(['code' => 200, 'msg' => '删除成功', 'data' => '']);
        }else{
            return json(['code' => 100, 'msg' => '删除失败', 'data' => '']);
        }
    }
    
    /**
     * 导出Excel
     * @return \think\response\Json
     */
    public function outExcel(){
        $params = input('param.');
        if($params['ids'] == "" && $params['in_name'] == "" && $params['spec_type_id'] == "" && $params['house_type_id'] == "" && $params['house_id'] ==""){
            $data = Db::table('up_in_warehouse')
                ->alias('uiw')
                ->join('up_u_user uuu', 'uuu.user_id = uiw.in_user_id', 'left')
                ->join('up_u_user uuu1', 'uuu1.user_id = uiw.check_user_id', 'left')
                ->join('up_house_type uht', 'uht.house_type_id = uiw.house_type_id', 'left')
                ->join('up_spec_type ust', 'ust.spec_type_id = uiw.spec_type_id', 'left')
                ->join('up_warehouse uw', 'uw.house_id = uiw.warehouse_id', 'left')
                ->field(['in_id', 'create_time', 'in_num', 'house_type', 'spec_type', 'warehouse_name',
                    'uuu.user_username', 'uuu1.user_username' => 'check_user', 'check_user_id',
                    'in_name', "concat('".http_type()."',in_img)"=>'in_img', 'in_status', 'in_abstract',
                'in_detail_address'])
                ->order('create_time desc')
                ->select();
        }
        $where = [];
        if($params['ids'] != ""){
            $ids = trim($params['ids'],',');
            $ids = explode(',',$ids);
            $where['in_id'] = ['IN', $ids];
//            $data = Db::name('in_warehouse')->where('in_id', 'IN', $ids)->select();
        }else{
            //名称
            if(isset($params['in_name']) && $params['in_name'] != "") {
                $where['uiw.in_name'] = ['like', "%" . $params['in_name'] . "%"];
            }
            //规格类型
            if(isset($params['spec_type_id']) && $params['spec_type_id'] != '') {
                $where['uiw.spec_type_id'] = $params['spec_type_id'];
            }
            //房屋类型
            if(isset($params['house_type_id']) && $params['house_type_id'] != '') {
                $where['uiw.house_type_id'] = $params['house_type_id'];
            }
            //仓库
            if(isset($params['house_id']) && $params['house_id'] != '') {
                $where['uiw.warehouse_id'] = $params['house_id'];
            }
        }
        $data = Db::table('up_in_warehouse')
            ->alias('uiw')
            ->join('up_u_user uuu', 'uuu.user_id = uiw.in_user_id', 'left')
            ->join('up_u_user uuu1', 'uuu1.user_id = uiw.check_user_id', 'left')
            ->join('up_house_type uht', 'uht.house_type_id = uiw.house_type_id', 'left')
            ->join('up_spec_type ust', 'ust.spec_type_id = uiw.spec_type_id', 'left')
            ->join('up_warehouse uw', 'uw.house_id = uiw.warehouse_id', 'left')
            ->field(['in_id', 'create_time', 'in_num', 'house_type', 'spec_type', 'warehouse_name',
                'uuu.user_username', 'uuu1.user_username' => 'check_user', 'check_user_id',
                'in_name', "concat('".http_type()."',in_img)"=>'in_img', 'in_status', 'in_abstract',
            'in_detail_address'])
            ->where($where)
            ->order('create_time desc')
            ->select();
        foreach($data as $key => &$vo){
            //审核者
            if($vo['check_user_id'] == -1) $vo['check_user'] = 'admin';
            //状态
            if($vo['in_status'] == 1){
                $vo['in_status'] = '审核中';
            }elseif($vo['in_status'] == 2){
                $vo['in_status'] = '审核通过';
            }else{
                $vo['in_status'] = '审核失败';
            }
        }
        $cellname = [
            ['in_id','ID',15,'LEFT'],
            ['in_name','名称',15,'LEFT'],
            ['in_num','单据编号',15,'LEFT'],
            ['in_img','缩略图',20,'LEFT'],
            ['house_type','房屋类型',15,'LEFT'],
            ['spec_type','规格类型',15,'LEFT'],
            ['warehouse_name','仓库',15,'LEFT'],
            ['in_status','状态',15,'LEFT'],
            ['create_time','入库时间',15,'LEFT'],
            ['user_username','经办人',15,'LEFT'],
            ['check_user','审核人',15,'LEFT'],
            ['in_abstract','摘要',30,'LEFT'] ,
            ['in_detail_address','详细地址',30,'LEFT']
        ];
        $res = exportExcel('库存列表','buildings',$cellname,$data);
        return json($res);
    }
    
    /**
     * @return \think\response\Json
     * 批量审核
     */
    public function audithAll(){
        $params = input('param.');
        if($params['ids'] == ''){
            $res = Db::table('up_in_warehouse')->field('in_status')->select();
        }else{
            $res = Db::table('up_in_warehouse')->where('in_id', 'IN', $params['ids'])->select();
        }
        
        foreach($res as $k => $v){
            if($v['in_status'] != 1){
                return json(['code' => 100, 'msg' => '有审核失败或审核成功的记录，请重新选择', 'data' => '']);
            }else{
                return json(['code' => 200, 'msg' => '', 'data' => $params['ids']]);
            }
        }
    }
    
    /**
     * @return mixed|\think\response\Json
     * 批量审核操作
     */
    public function doAuditAll(){
        if(Request::instance()->isPost()){
            $ids = input('ids');
            $ids = trim($ids,',');
            $ids = explode(',',$ids);
            $in_status = input('in_status');
            Db::startTrans();
            try{
                foreach($ids as $k=>$v){
                    $data = [
                        'in_status' => $in_status,//状态  2 通过  2 不通过
                        'check_user_id' => -1,//审核者，后台审核时为-1
                        'check_time' => date('Y-m-d H:i:s'),//审核时间
                    ];
                    Db::table('up_in_warehouse')->where('in_id', $v)->update($data);
                }
                Db::commit();
                $res = true;
            }catch(\Exception $e){
                Db::rollback();
                $res = false;
            }
            if($res){
                return json(['code' => 200, 'msg' => '审核成功', 'data' => '']);
            }else{
                return json(['code' => 100, 'msg' => '审核失败', 'data' => '']);
            }
        }
        $ids = input('ids');
        $this->assign('ids', $ids);
        return $this->fetch('doauditall');
    }
    
    /**
     * @return mixed
     * 导入Excel
     */
    public function excelIn(){
        if(request()->file('file')){
            $file = request()->file('file');
            $info  = $file->getInfo();
            $file_path = $info['tmp_name'];
            //取出文件后缀
            $file_type = explode(".",$info['name']);
            $file_type = end($file_type);
            vendor("PHPExcel.PHPExcel.IOFactory");
            if( $file_type == 'xls' ){
                $inputFileType = 'Excel5';    //这个是读 xls的
            }else{
                $inputFileType = 'Excel2007';//这个是计xlsx的
            }
            $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
            $objPHPExcel = $objReader->load($file_path);
            $objWorksheet = $objPHPExcel->getActiveSheet();
            $highestRow = $objWorksheet->getHighestRow();
//            print_r($highestRow);die;
            for ($i=2;$i<=$highestRow;$i++) {
                $a = $objPHPExcel->getActiveSheet ()->getCell ("A" . $i)->getValue ();//获取A列的值
                $b = $objPHPExcel->getActiveSheet ()->getCell ("B" . $i)->getValue ();//获取B列的值
                $c = $objPHPExcel->getActiveSheet ()->getCell ("C" . $i)->getValue ();//获取C列的值
                $d = $objPHPExcel->getActiveSheet ()->getCell ("D" . $i)->getValue ();//获取D列的值
                $e = $objPHPExcel->getActiveSheet ()->getCell ("E" . $i)->getValue ();//获取E列的值
                $f = $objPHPExcel->getActiveSheet ()->getCell ("F" . $i)->getValue ();//获取F列的值
                //前缀
                $spec_name = Db::table('up_spec_type')->where('spec_type_id', $c)->value('spec_code');
                $param = [
                    'in_num' => $spec_name . '-' . date('YmdHis') . rand(0000,9999),//编号
                    'in_name' => $a,//名称
                    'house_type_id' => $b,//房屋类型
                    'spec_type_id' => $c,//规格类型
                    'warehouse_id' => $d,//仓库ID
                    'in_address' => $e,//地址
                    'in_abstract' => $f,//摘要
                    'in_status' => 1,//审核状态
                    'create_time' => date('Y-m-d H:i:s'),//入库时间
                    'in_user_id' => 0,//入库者ID
                ];
                Db::name('in_warehouse')->insert($param);
            }
            echo '/admin/building/index';
        }
        return $this->fetch('building/excelin');
    }
}